package com.derbysoft.ota.application.util;

import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.xml.transform.StringResult;

import util.Jaxb2MarshallerHolder;

import com.google.common.base.Preconditions;

public abstract class Jaxb2Marshallers {
	
	public static String marshall(Jaxb2Marshaller jaxb2Marshaller, Object o) {
		Result result = new StringResult();
		jaxb2Marshaller.marshal(o, result);
		return result.toString();
	}
	
	public static <T> T unmarshall(String fileName, Class<T> expectedType) {
		return unmarshall(
			new StreamSource(
				Preconditions.checkNotNull(
					Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName),
					"Resource [" + fileName + "] not found."
				)
			), 
			expectedType
		);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T unmarshall(StreamSource source, Class<T> expectedType) {
		return (T) Jaxb2MarshallerHolder.get().unmarshal(source);
	}
}
